import Taro, { Component } from '@tarojs/taro';
import { View, Text, Button, Image } from '@tarojs/components';
import GoodsImage from '../../static/home/banner.png';
import './index.scss';
import { getOrderList, deleteOrder, deliveryOrder, orderCheck, testPay, orderPay } from '../../../services/order';
import { ORDER_STATUS } from '../../../utils/config';
import NavigationBar from '../../../components/navigationBar/index';
import { fullImgUrl } from '../../../utils/utils';
import Empty from '../../../static/public/icon_order.png';
import UpdateModal from '../../../components/update-modal/index';
import selected from './img/selected.png';
import fselected from './img/fselected.png';
export default class Index extends Component {

  config = {
    navigationBarTitleText: '我的订单',
    enablePullDownRefresh: true,
  }

  state = {
    isShowUpdateModal: false,
    UpdateOrderInfo: null,
    activeIndex: 0,
    orderList: [],
    pageData: {
      page: 1,
      page_number: 10,
      order_type: 8,
      order_status: 4,
      is_receipt:1
    },
    isMore: false,
    tab2order: [-1, 0, 2, 3, 4, 1],
    navigationBarHeight: Taro.getStorageSync('navigationBarHeight'),
    selectAllStatus: false // 全选状态，默认全选

  }

  componentWillMount() {
  }
  componentDidMount() { }
  componentWillReceiveProps(nextProps, nextContext) { }
  componentWillUnmount() { }
  componentDidShow() {
    this.changeTab();
  }
  componentDidHide() { }
  componentDidCatchError() { }
  componentDidNotFound() { }

  onPullDownRefresh() {
    console.log('pull donw');
    Taro.showLoading({
      mask: true
    })
    this.changeTab();
  }

  onReachBottom() {
    console.log('reach bottom');
    if (this.state.isMore) {
      getOrderList({
        order_status: this.state.tab2order[this.state.activeIndex],
        ...this.state.pageData
      }).then(res => {
        console.log(res)
        res.list.forEach(item => {
          item.selected = true

          item.has_order_goods_sku[0].cover = fullImgUrl(item.has_order_goods_sku[0].cover)
        })
        let temp = this.state.orderList
        temp = temp.concat(res.list)
        let pageData = this.state.pageData;
        pageData.page++;
        this.setState({
          orderList: temp,
          isMore: temp.length < res.total,
          pageData
        })
      })
    }
  }

  changeTab(index, e) {
    this.setState({
      isMore: false,
    }, () => {
      getOrderList({
        ...this.state.pageData
      }).then(res => {
        console.log(res)
        res.list.forEach(item => {
          item.has_order_goods_sku[0].cover = fullImgUrl(item.has_order_goods_sku[0].cover)
        })
        let pageData = this.state.pageData;
        pageData.page++;
        this.setState({
          orderList: res.list,
          isMore: res.list.length < res.total,
          pageData
        }, () => {
          Taro.stopPullDownRefresh();
          Taro.hideLoading()
        })
      })
    });
  }

  delOrder(orderId) {
    let self = this;
    Taro.showModal({
      title: '提示',
      content: '删除后不可恢复,你确定要删除吗？',
      success: function (res) {
        if (res.confirm) {
          deleteOrder({
            order_info_id: orderId
          }).then(res => {
            let temp = [...self.state.orderList];
            temp = temp.filter(item => {
              return item.order_info_id !== orderId;
            })
            self.setState({
              orderList: temp
            });
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    });
  }

  onScrollToLower = () => {
    console.log('下拉加载更多');
    if (this.state.isMore) {
      getOrderList({
        order_status: this.state.tab2order[this.state.activeIndex],
        ...this.state.pageData
      }).then(res => {
        console.log(res)
        res.list.forEach(item => {
          item.has_order_goods_sku[0].cover = fullImgUrl(item.has_order_goods_sku[0].cover)
        })
        let temp = this.state.orderList
        temp = temp.concat(res.list)
        let pageData = this.state.pageData;
        pageData.page++;
        this.setState({
          orderList: temp,
          isMore: temp.length < res.total,
          pageData
        })
      })
    }
  }

  goOrderDetail(orderId) {
    // Taro.navigateTo({
    //   url: `/subPackageWork/pages/order-detail/index?id=${orderId}`
    // })
  }

  applyInvoice(orderId) {

  }
  selectList(id, e) {
    let carts = this.state.orderList
    carts.forEach(item => {
      if (id == item.order_info_id) {
        item.selected = !item.selected
      }
    })
    // const checkall = this.data.selectAllStatus === true ? false : false
    this.setState({
      orderList: carts,
      // selectAllStatus: false
    })
    const selectAllStatus = carts.every(item => item.selected)
    this.setState({
      selectAllStatus: selectAllStatus
    })
  }
  selectAll(e) {
    let selectAllStatus = this.state.selectAllStatus
    selectAllStatus = !selectAllStatus
    let carts = this.state.orderList

    for (let i = 0; i < carts.length; i++) {
      carts[i].selected = selectAllStatus
    }
    this.setState({
      selectAllStatus: selectAllStatus,
      orderList: carts
    })
  }
  checkOrder(orderId) {
    orderCheck({
      order_info_id: orderId
    }).then(res => {
      let temp = [...this.state.orderList];
      for (let i = 0; i < temp.length; i++) {
        if (temp[i].order_info_id === orderId) {
          temp[i].order_status = 4;
          break;
        }
      }
      console.log(temp);
      this.setState({
        orderList: temp
      });
    })
  }

  goPay(orderId) {
    let self = this
    orderPay({
      order_id: orderId,
      // pay_type: 1,
      pay_type: 3,
      pay_platform: 1
    }).then(data => {
      Taro.requestPayment({
        // ...data,
        ...(JSON.parse(data.payload).metadata),
        success() {
          self.changeTab(0)
        },
        fail() {
          console.log('not ok')
        }
      })
    })
  }

  checkExpress(order) {
    Taro.navigateTo({
      url: `/subPackageWork/pages/express-status/index?id=${order.order_info_id}`
    })
  }

  update(order) {
    this.setState({
      isShowUpdateModal: true,
      UpdateOrderInfo: order,
    })
  }

  updateAddress(order) {
    Taro.navigateTo({
      url: `/subPackageWork/pages/my-address/index?orderId=${order.order_info_id}`
    });
  }
  shopgopurchase() {
    var arr = []
    this.state.orderList.forEach(ele => {
      if (ele.selected == true) {
        arr.push(ele.order_info_id)
      }
    })
    // if (!this.state.deliveryTime) {
    //   Taro.showToast({
    //     title: '请选择发货时间!',
    //     icon: 'none'
    //   });
    // } else {
    //   if (arr.length > 0) {
    //     ShoppingCartEdit({
    //       ...arredit
    //     }).then(res => {
    if (arr.length == 0) {
      Taro.showToast({
        title: '请选择订单',
        icon: 'none'
      });
    } else {
      console.log(JSON.stringify(arr))
      Taro.navigateTo({
        url: `/subPacKagebWork/pages/apply-invoice/index?id=${JSON.stringify(arr)}`
      })
    }

  }
  cancelModal() {
    this.setState({
      isShowUpdateModal: false,
    })
  }

  render() {
    let { orderList, isShowUpdateModal, UpdateOrderInfo, selectAllStatus } = this.state;
    return (
      <View className="my-order" style={`margin-top: ${navigationBarHeight}`}>
        <NavigationBar text="批量申请发票" type="activity" />
        <ScrollView
          className='order-list'
          scrollY
          scrollWithAnimation
          onScrollToLower={this.onScrollToLower}
        >
          <View>
            {orderList.length ? orderList.map((order, index) => {
              return <View className={'order-card'} key={order.id}>
                <View className="top">
                  <View className="order-id">订单号:{order.order_sn}</View>
                  <View className="order-status ready-pay">{ORDER_STATUS[order.order_status]}</View>
                </View>
                <View className="middle" onClick={this.goOrderDetail.bind(this, order.order_info_id)}>
                  {order.selected ? (
                    <Image data-index={index} className="cart-pro-select" onClick={this.selectList.bind(this, order.order_info_id)} src={
                      fselected
                    }></Image>
                  ) : (
                      <Image data-index={index} className="cart-pro-select" onClick={this.selectList.bind(this, order.order_info_id)} src={
                        selected
                      }></Image>
                    )}
                  <Image className="goods-image" src={order.has_order_goods_sku[0].cover} alt="商品图" />
                  <View className="order-info">
                    <View className="goods-name">{order.has_order_goods_sku[0].goods_name}</View>
                    <View className="goods-desc">{order.has_order_goods_sku[0].has_order_goods_attr.map((attr, index) => {
                      return <Text key={attr.id}>{attr.goods_sku_attr_name + ' '}</Text>;
                    })}</View>
                    <View className="goods-specification">
                      <View className="goods-number">数量: {order.has_order_goods_sku[0].num}</View>
                      <View className="goods-price">¥ {order.paid_amount}</View>
                    </View>
                  </View>
                </View>
                <View className="bottom">
                  {/* {order.order_status === 0 && <View onClick={this.goPay.bind(this, order.order_info_id)} className="opt-btn to-pay">去支付</View>}
                {order.order_status === 3 && <View className="opt-btn check-order" onClick={this.checkOrder.bind(this, order.order_info_id)}>确认收货</View>}
                {order.order_status === 3 && <View onClick={this.checkExpress.bind(this, order)} className="opt-btn look-logistics">查看物流</View>}
                {order.order_status === 2 && !order.is_update_delivery_time && <View onClick={this.update.bind(this, order)} className="opt-btn update">修改时间</View>}
                {order.order_status === 2 && !order.is_update_address && <View onClick={this.updateAddress.bind(this, order)} className="opt-btn update">修改地址</View>} */}
                  {/* {(order.order_status === 3 || order.order_status === 4 || order.order_status === 2) && !order.is_receipt && <View className="opt-btn request-invoice" onClick={this.applyInvoice.bind(this, order.order_info_id)}>申请发票</View>} */}
                  {/* {(order.order_status === 1 || order.order_status === 4) && <View className="opt-btn del-order" onClick={this.delOrder.bind(this, order.order_info_id)}>删除订单</View>} */}
                </View>
              </View>
            }) : <View className="empty-box">
                <Image src={Empty} className="empty" />
                <View className="tip">暂无订单信息</View>
              </View>}
          </View>
        </ScrollView>
        <View className="commonfooter">
          <View style='display:flex;align-items: center;'>
            {selectAllStatus ? (
              <Image data-index={index} className="cart-pro-select" onClick={this.selectAll.bind()} src={
                fselected
              }></Image>
            ) : (
                <Image data-index={index} className="cart-pro-select" onClick={this.selectAll.bind()} src={
                  selected
                }></Image>
              )}
            <View className="bigmoneyFu">全选</View>
          </View>
          <View onClick={this.shopgopurchase} className="wechart">申请发票</View>
        </View>
        {isShowUpdateModal && <UpdateModal orderInfo={UpdateOrderInfo} cancel={this.cancelModal.bind(this)} />}
      </View>
    );
  }
}
